
package com.kanjian.music.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.kanjian.music.R;
import com.kanjian.music.fragment.DownloadedMusicFragment;
import com.kanjian.music.fragment.DownloadingMusicFragment;
import com.kanjian.music.fragment.PlayOnDownloadMusicFragment;

public class DownloadActivity extends BaseActivity {

    private Button mBtn_downloaded;
    
    private Button mBtn_downloadOnPlay;

    private Button mBtn_downloading;

    private DownloadedMusicFragment mDownloadedFragment = new DownloadedMusicFragment();
    
    private PlayOnDownloadMusicFragment mPlayOnDownloadMusicFragment = new PlayOnDownloadMusicFragment();

    private DownloadingMusicFragment mDownloadingFragment = new DownloadingMusicFragment();

    private FragmentTransaction mFragmentTransaction;
    
    private Fragment mShowingFragment = mDownloadedFragment;

    @Override
    protected void onCreate(Bundle arg0) {
        setContentView(R.layout.activity_download_list);
        super.onCreate(arg0);
        initView();
    }

    private void initView() {
        mBtn_downloaded = (Button) findViewById(R.id.download_list_btn_downloaded);
        mBtn_downloadOnPlay = (Button) findViewById(R.id.download_list_btn_downloadonplay);
        mBtn_downloading = (Button) findViewById(R.id.download_list_btn_downloading);
        
        mBtn_downloaded.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFragment(mDownloadedFragment, mShowingFragment);
            }
        });
        mBtn_downloading.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFragment(mDownloadingFragment, mShowingFragment);
            }
        });
        
        mBtn_downloadOnPlay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				toggleFragment(mPlayOnDownloadMusicFragment, mShowingFragment);
			}
		});
        
        toggleFragment(mDownloadedFragment, mDownloadingFragment);
    }

    private void toggleFragment(Fragment showFragment, Fragment hideFragment) {
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (hideFragment != null && hideFragment.isAdded() && !hideFragment.isHidden()) {
            mFragmentTransaction.hide(hideFragment);
        }
        if (showFragment != null) {
            if (!showFragment.isAdded()) {
                mFragmentTransaction.add(R.id.download_list_fragment_container, showFragment);
            } else {
                mFragmentTransaction.show(showFragment);
            }
        }
        mFragmentTransaction.commitAllowingStateLoss();
    }

}
